<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>临时聊天室</title>
    <link rel="stylesheet" href="assets/all.min.css">
    <link rel="stylesheet" href="index.css">
</head>
<body>
<div class="container">
    <!-- 侧边栏 -->
    <div class="sidebar">
        <div class="sidebar-header">
            <h2>聊天室</h2>
        </div>

        <div class="tab-buttons">
            <button class="tab-btn active" data-tab="rooms">房间</button>
            <button class="tab-btn" data-tab="users">用户</button>
        </div>

        <div class="sidebar-content">
            <!-- 房间列表 -->
            <div class="tab-content active" id="rooms">
                <button id="new-room-btn" class="list-item"
                        style="background-color: #e6f0ff; color: var(&#45;&#45;primary-color); justify-content: center;">
                    <i class="fas fa-plus" style="margin-right: 8px;"></i>
                    新建房间
                </button>
            </div>

            <!-- 用户列表 -->
            <div class="tab-content" id="users"></div>
        </div>
    </div>

    <!-- 主聊天区域 -->
    <div class="chat-area">
        <!-- 顶部红色滚动文字 -->
        <div class="scrolling-notice">
            <marquee scrollamount="10" direction="left" style="color: red;">
                刷新页面数据删除！！本聊天软件不存储聊天记录数据。图片、视频仅保存30分钟用于数据展示，30分钟后自动销毁。
            </marquee>
        </div>

        <div class="chat-header">
            <div class="room-info">
                <h3></h3>
                <p></p>
            </div>
        </div>

        <div class="chat-messages"></div>

        <div class="chat-input">
            <!-- 预览区域 -->
            <div class="preview-container" id="preview-container"></div>
            <div class="input-group">
                <div class="input-actions">
                    <button title="发送图片" id="image-btn">
                        <i class="fas fa-image"></i>
                        <input type="file" id="image-input" class="file-input" accept="image/*" multiple>
                    </button>
                    <button title="发送视频" id="video-btn">
                        <i class="fas fa-video"></i>
                        <input type="file" id="video-input" class="file-input" accept="video/*" multiple>
                    </button>
                </div>
                <div class="send-input">
                    <div class="input-wrapper">
                        <input type="text" id="message-input" placeholder="输入消息..." autocomplete="off">
                        <button class="send-btn" id="send-btn"><i class="fas fa-paper-plane"></i> 发送</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 新建房间模态框 -->
<div class="modal" id="new-room-modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>新建房间</h3>
            <button class="close">&times;</button>
        </div>
        <div class="modal-body">
            <div class="form-group">
                <label for="room-name">房间名称</label>
                <input type="text" id="room-name" placeholder="例如: 技术讨论">
            </div>
            <!--<div class="form-group">
                <label for="room-password">房间密码</label>
                <input type="text" id="room-password" placeholder="例如: 123456">
            </div>
            <div class="form-group">
                <label for="room-privacy">隐私设置</label>
                <select id="room-privacy">
                    <option value="public">公开 - 任何人都可以加入</option>
                    <option value="private">私有 - 需要邀请才能加入</option>
                </select>
            </div>-->
        </div>
        <div class="modal-footer">
            <button class="cancel">取消</button>
            <button class="submit">创建房间</button>
        </div>
    </div>
</div>
<script src="assets/ip.js"></script>
<script src="baseUtils.js"></script>
<script src="assets/axios.min.js"></script>
<script src="assets/spark-md5.min.js"></script>
<script src="assets/crypto-js.min.js"></script>
<script src="assets/jquery.min.js"></script>
<script src="assets/chunkUploader.js"></script>
<script src="assets/websocket-util.js"></script>
<script src="room-user.js"></script>
<script src="index.js"></script>

<script>
    let wxUtil, user, roomId, toUserId, userId, userName;
    (async function () {
        await getPublicIP();
        let ip = sessionStorage.getItem('publicIP');
        console.log("对应IP地址",sessionStorage.getItem('publicIP'))
        user = await getUserId(ip);
        toUserId = await getUrlSearch("userId");
        userId = user.data.userId;
        userName = user.data.userName;
        await queryRoomFun();
        // 在实际应用中，这里应该发送请求到服务器创建房间
        wxUtil = new WebSocketUtil(wsBaseUrl+'?token=' + userId, {
            heartbeatInterval: 5000,
            onOpen: () => {
                wxUtil.sendBindMessage(userId);
                mes = {
                    type: 'regist',
                    userId: userId,
                    userName: userName,
                }
                wxUtil.sendMessage(userId, mes)
            }
        });
        // 处理收到的信令消息
        wxUtil.addMessageHandler((data) => {
            switch (data.type) {
                case 'msg':
                    const conent = data.content;
                    const messagesContainer = document.querySelector('.chat-messages');
                    const replyMessage = document.createElement('div');
                    replyMessage.className = 'message';
                    replyMessage.innerHTML = `
                            <div class="content">
                                <div class="info">
                                    <h4>${data.fromName}</h4>
                                    <time>${new Date().toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'})}</time>
                                </div>
                                <div class="text">
                                    ${conent.msg}
                                </div>
                            </div>
                        `;
                    messagesContainer.appendChild(replyMessage);
                    //图片视频
                    if (conent.file.length > 0) {
                        // 添加媒体内容
                        conent.file.forEach(media => {
                            if (media.type === 'image') {
                                replyMessage.querySelector('.content').innerHTML += `
                                        <div class="media">
                                            <img src="${media.url}" alt="图片">
                                        </div>
                                    `;
                            } else {
                                const lastDot = media.url.lastIndexOf('.');
                                const types = media.url.slice(lastDot + 1);
                                replyMessage.querySelector('.content').innerHTML += `
                                        <div class="media">
                                            <video controls>
                                                <source src="${media.url}" type="${media.url}/${types}">
                                                您的浏览器不支持视频播放
                                            </video>
                                        </div>
                                    `;
                            }
                        });
                        updatePreview();
                    }
                    messagesContainer.scrollTop = messagesContainer.scrollHeight;
                    break
                case "join-room":
                    document.getElementById(data.user.userId)?.remove();
                    document.querySelector('.room-info p').textContent = `${data.userCount}人在线`;
                    let user = data.user;
                    addUser(user);
                    break;
                case "leave-room":
                    document.querySelector('.room-info p').textContent = `${data.userCount}人在线`;
                    document.getElementById(data.user.userId).remove();
                    break;
                case "room-count":
                    $("#" + data.roomId).find('p').html(`${data.userCount}人在线`);
                    break;
            }
        });
    })();
    // 切换标签页
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.addEventListener('click', async () => {
            // 移除所有活动标签
            document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));

            // 添加活动类到当前标签
            btn.classList.add('active');
            const tabId = btn.getAttribute('data-tab');
            if (tabId == 'users') {
                if(!document.querySelector('#rooms .active')){
                    return;
                }
                roomId = document.querySelector('#rooms .active').id;
                const userList = await queryRoomUser(roomId);
                const usersList = document.getElementById('users');
                usersList.innerHTML = '';
                userList.data.forEach(item => addUser(item));
            } else if (tabId == 'rooms') {
                await queryRoomFun();
            }
            document.getElementById(tabId).classList.add('active');
        });
    });
    // 新建房间按钮
    const newRoomBtn = document.getElementById('new-room-btn');
    const newRoomModal = document.getElementById('new-room-modal');
    const closeModal = document.querySelector('.modal .close');
    const cancelModal = document.querySelector('.modal .cancel');
    // 显示新建房间模态框
    newRoomBtn.addEventListener('click', () => {
        newRoomModal.classList.add('active');
    });

    // 关闭模态框 - 点击关闭按钮(X)
    closeModal.addEventListener('click', () => {
        newRoomModal.classList.remove('active');
    });

    // 关闭模态框 - 点击取消按钮
    cancelModal.addEventListener('click', () => {
        newRoomModal.classList.remove('active');
    });

    // 关闭模态框 - 点击模态框外部区域
    newRoomModal.addEventListener('click', (e) => {
        if (e.target === newRoomModal) {
            newRoomModal.classList.remove('active');
        }
    });

    // 创建房间提交
    document.querySelector('.modal .submit').addEventListener('click', async () => {
        const roomName = document.getElementById('room-name').value;
        // const roomPassword = document.getElementById('room-password').value;
        const roomPassword = "";
        if (!roomName) {
            alert('请填写房间名称');
            return;
        }

        let data ={
            roomName,
            roomPassword,
            userId
        }
        await createRoom(data);
        // 关闭模态框
        newRoomModal.classList.remove('active');
        // 清空表单
        document.getElementById('room-name').value = '';
        /*
        document.getElementById('room-password').value = '';
        document.getElementById('room-privacy').value = 'public';
        */
        await queryRoomFun();
    });

    // 发送消息
    document.querySelector('.chat-input .input-group .send-input button').addEventListener('click', sendMessage);
    document.querySelector('.chat-input .input-group .send-input input').addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });

    // 多媒体消息功能
    const imageBtn = document.getElementById('image-btn');
    const videoBtn = document.getElementById('video-btn');
    const imageInput = document.getElementById('image-input');
    const videoInput = document.getElementById('video-input');
    const previewContainer = document.getElementById('preview-container');

    // 存储待发送的媒体文件
    let mediaFiles = [];

    // 图片按钮点击
    imageBtn.addEventListener('click', () => {
        imageInput.click();
    });

    // 视频按钮点击
    videoBtn.addEventListener('click', () => {
        videoInput.click();
    });

    // 图片选择处理
    imageInput.addEventListener('change', (e) => {
        handleFiles(e.target.files, 'image');
        e.target.value = ''; // 清空输入以便重复选择
    });

    // 视频选择处理
    videoInput.addEventListener('change', (e) => {
        handleFiles(e.target.files, 'video');
        e.target.value = ''; // 清空输入以便重复选择
    });

</script>
</body>
</html>
